package org.dromara.basic.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.dromara.basic.domain.bo.MemberBo;
import org.dromara.basic.domain.vo.MemberVo;
import org.dromara.basic.domain.vo.TeachClassVo;
import org.dromara.basic.service.IMemberService;
import org.dromara.basic.service.ITeachClassService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;


import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class MemberInfoListener extends AnalysisEventListener<MemberVo> implements ExcelListener<MemberVo> {

    private ExecutorService globalThreadPool;

    private final IMemberService memberService;
    private final ITeachClassService teachClassService;
    private final Boolean isUpdateSupport;
    private final Long operUserId;
    private final String tenantId;

/*    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();*/
    // 使用线程安全的计数器
    private final AtomicInteger successNum = new AtomicInteger(0);
    private final AtomicInteger failureNum = new AtomicInteger(0);
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public MemberInfoListener(Boolean isUpdateSupport) {
        this.memberService = SpringUtils.getBean(IMemberService.class);
        this.teachClassService = SpringUtils.getBean(ITeachClassService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operUserId = LoginHelper.getUserId();
        this.tenantId = LoginHelper.getTenantId();
//        this.globalThreadPool=SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public ExcelResult<MemberVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum.get() > 0) {
                    failureMsg.insert(0, "很抱歉，用户详细信息导入失败！共 " + failureNum.get() + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，用户详细信息数据已全部导入成功！共 " + successNum.get() + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<MemberVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }

    @Override
    public void invoke(MemberVo memberVo, AnalysisContext analysisContext) {
        MemberVo member = this.memberService.queryByIdNumber(memberVo.getIdNumber());
        TeachClassVo teachClassVo = this.teachClassService.queryByClassName(memberVo.getClassName());
        try {
            //验证是否有这个读者
            if (ObjectUtil.isNull(member)) {
                MemberBo memberBo = BeanUtil.toBean(memberVo, MemberBo.class);
                ValidatorUtils.validate(memberBo);
                memberBo.setCreateBy(operUserId);
                if(ObjectUtil.isNotNull(teachClassVo)){
                    memberBo.setClassId(teachClassVo.getClassId());
                }
                memberBo.setFileType("studentInfo");
                String filePath = FileUploadUtils.getFilePath(memberBo,tenantId);
                if(StringUtils.isNotEmpty(filePath)){
                    memberBo.setFaceImage(filePath);
                }
                memberService.insertByBo(memberBo, false);
                int currentSuccess = successNum.incrementAndGet();
                synchronized (successMsg) {
                    successMsg.append("<br/>").append(currentSuccess).append("、学生信息 ").append(memberBo.getName()).append(" 导入成功");
                }
            } else if (isUpdateSupport) {
                Long stuId = member.getMemberId();
                MemberBo memberBo = BeanUtil.toBean(memberVo, MemberBo.class);
                memberBo.setMemberId(stuId);
                ValidatorUtils.validate(memberBo);
                if(ObjectUtil.isNotNull(teachClassVo)){
                    memberBo.setClassId(teachClassVo.getClassId());
                }
                memberBo.setFileType("studentInfo");
                String filePath = FileUploadUtils.getFilePath(memberBo,tenantId);
                if(StringUtils.isNotEmpty(filePath)){
                    memberBo.setFaceImage(filePath);
                }
                memberBo.setUpdateBy(operUserId);
                memberService.updateByBo(memberBo,false);
                int currentSuccess = successNum.incrementAndGet();
                synchronized (successMsg) {
                    successMsg.append("<br/>").append(currentSuccess).append("、学生信息 ").append(memberBo.getName()).append(" 更新成功");
                }
            } else {
                int currentFailure = failureNum.incrementAndGet();
                synchronized (failureMsg) {
                    failureMsg.append("<br/>").append(currentFailure).append("、学生信息 ").append(memberVo.getName()).append(" 已存在");
                }
            }
        } catch (Exception e) {
            int currentFailure = failureNum.incrementAndGet();
            String msg = "<br/>" + currentFailure + "、学生信息 " + memberVo.getName() + " 导入失败：";
            synchronized (failureMsg) {
                failureMsg.append(msg).append(e.getMessage());
            }
            log.error(msg, e);
        }
        // 使用线程池执行任务
//        globalThreadPool.execute(task);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
